<template>
	<view class="content1">
		<uni-nav-bar shadow color="#000" background-color="#ffffff" status-bar left-icon="left" right-icon="more-filled"
			title="给TA留言" @clickLeft="back" @clickRight="back" />

		<view class="leave_content page_body max-width">
			<!-- 留言背景 -->
			<view class="treeleavebg">
				<view class="treeleavebg_bg">
				</view>
			</view>
			<!-- 内容 -->
			<view class="treele_box">

				<!-- 信件内容 -->
				<view class="treeleask treelecho_panel">
					<view class="treeleask_box">
						<view class="treeleask_content">
							<text>亲爱的陌生人！\n</text>
							<text style="margin-left: 28px;">你好！\n</text>
							<view class="treelecontent" v-if="letter.content">{{ letter.content }}</view>
							<view class="treeleask_person">
								<image src='../../static/img/default_avatar.70f94228.png' mode="aspectFit"
									style="height: 25px;width: 25px;margin-right: 2px"></image>
								<text class="treeleask_name">{{ letter.sign }}</text>
							</view>
							<view class="treeleask_time">{{ letter.creationTime | formatDate }}</view>
						</view>
					</view>
				</view>
				<!-- 留言内容 -->
				<view class="treeleanswer treelecho_panel">
					<view class="treeleanswer_box">
						<view class="treeleanswer_editor">
							<view class="leavetextarea treeleanswer_textarea">
								<textarea placeholder="愿你的温暖回应，能成为照亮他人的光" placeholder-style="color:#d6ccb1;"
									class="leavetextarea_ta" style="min-height: 140px;height: 140px;" maxlength="2000"
									v-model="content" @input="handleInput"></textarea>
							</view>
						</view>
					</view>
				</view>
				<!-- 发布 -->
				<view class="treeholeecho_btn-publish fw-medium is-disabled" :class="{ 'is-disabled': wordCount === 0 }"
					:style="buttonStyle" @click="submitComment">
					<text class="fabu">{{ buttonText }}</text>
				</view>

				<!-- 提示窗口 -->
				<view v-if="showWarning" class="warning-message">
					<text>请输入留言内容</text>
				</view>
				<!-- 匿名发布 字数统计 -->
				<view class="businesspinbox ">
					<view class="businesspinbox_placeholder" style="height: 46px;"></view>
					<view class="businesspinbox_realbody businesspinbox_fixed" style="bottom: 0px;">
						<view class="treeholetoolbar_op">
							<view class="treeholetoolbar_anonymous flex">
								<image src="../../static/img/未选中圆圈.svg" mode="aspectFit"
									style="height: 20px;width: 20px;"></image>
								<text>匿名发布</text>
							</view>
							<view class="count">
								<text class="word-count">{{ wordCount }}/2000</text>
							</view>
						</view>
					</view>
				</view>

			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				content: "",
				wordCount: 0, // 字数统计
				showWarning: false,
				letter: {},
				currentUserID: null,
				currentUserPhone: null
			}
		},
		computed: {
			buttonStyle() {
				return {
					backgroundColor: this.wordCount > 0 ? '#f9d681' : '#868e99', // 根据字数改变背景色
					color: this.wordCount > 0 ? '#0b1d29' : '#cfd2d4', // 根据字数改变文字颜色
				};
			},
			buttonText() {
				return this.wordCount > 0 ? '发布' : '发布';
			}
		},
		onLoad(options) {
			this.currentUserID = uni.getStorageSync('userId');
			this.currentUserPhone = uni.getStorageSync('phone');
			if (!options || !options.messageId) {
				console.error('消息ID缺失或未定义');
				return;
			}
			console.log('接收到的消息ID:', options.messageId);
			if (!isNaN(options.messageId)) {
				this.getLetterDetail(parseInt(options.messageId, 10)).then(() => {
					// 数据获取完成后，再执行提交评论的操作
				});
			} else {
				console.error('无效的消息ID参数');
			}
		},
		filters: {
			formatDate(value) {
				const date = new Date(value);
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
			}
		},
		methods: {
		    handleInput(e) {
		        this.content = e.target.value; // 获取输入的内容
		        this.wordCount = this.content.length; // 计算字数
		        // 当有输入时，隐藏警告
		        if (this.wordCount > 0) {
		            this.showWarning = false;
		        }
		    },
		    submitComment() {
		        if (this.wordCount === 0) {
		            this.showWarning = true;
		            setTimeout(() => {
		                this.showWarning = false;
		            }, 4000);
		            return;
		        }
		
		        this.showWarning = false;
		
		        if (this.letter && this.letter.id) {
		            const url = `http://localhost:8080/letter/comments/add`;
		
		            // 获取当前时间戳并格式化
		            const currentTime = this.formatDate(new Date());
		
		            // 构建请求数据
		            const commentData = {
		                messagesId: this.letter.id,
		                content: this.content.trim(), // 确保评论文本不为空
		                userId: this.currentUserID,
		                userPhone: this.currentUserPhone,
		                creationTime: currentTime, // 添加格式化后的时间戳
		                commentText: this.content.trim() // 确保包含 commentText 字段
		            };
		
		            // 显示加载状态
		            uni.showLoading({
		                title: '提交中...'
		            });
		
		            uni.request({
		                url: url,
		                method: 'POST',
		                header: {
		                    'Content-Type': 'application/json;charset=UTF-8'
		                },
		                data: commentData,
		                success: (res) => {
		                    uni.hideLoading(); // 隐藏加载状态
		                    console.log('评论提交成功:', res);
		                    if (res.statusCode === 200 && res.data) {
		                        const responseData = res.data;
		                        if (responseData.code === 200) {
		                            uni.showToast({
		                                title: '评论成功',
		                                icon: 'success'
		                            });
		                            // 清空输入框
		                            this.content = '';
		                            this.wordCount = 0;
		                            uni.navigateBack();
		                        } else {
		                            console.error('评论提交失败:', responseData.msg || '未知错误');
		                            uni.showToast({
		                                title: '评论失败，请稍后再试',
		                                icon: 'none'
		                            });
		                        }
		                    } else {
		                        console.error('评论提交失败:', res);
		                        uni.showToast({
		                            title: '评论失败，请稍后再试',
		                            icon: 'none'
		                        });
		                    }
		                },
		                fail: (err) => {
		                    uni.hideLoading(); // 隐藏加载状态
		                    console.error('评论提交失败:', err);
		                    uni.showToast({
		                        title: '网络请求失败，请检查网络连接',
		                        icon: 'none'
		                    });
		                }
		            });
		        } else {
		            console.error('尝试提交评论时，messageID 未定义');
		            uni.showToast({
		                title: '无法提交评论，请稍后再试',
		                icon: 'none'
		            });
		        }
		    },
		    back() {
		        console.log("返回");
		        uni.navigateBack();
		    },
		    getLetterDetail(messageId) {
		        const url = `http://localhost:8080/letter/messages/detail/${messageId}`;
		        console.log('正在从服务器获取信件详情:', url);
		        uni.request({
		            url: url,
		            method: 'GET',
		            success: (res) => {
		                console.log('接收到的响应:', res);
		                if (res.statusCode === 200 && res.data) {
		                    this.letter = {
		                        ...res.data,
		                        id: res.data.messageID, // 确保id存在
		                        timestamp: new Date(res.data.creationTime)
		                    };
		                    this.isDataLoaded = true;
		                    const data = res.data.data;
		                    this.letter.content = data.content;
		                    this.letter.avatar = data.avatar;
		                    this.letter.sign = data.sign;
		                    this.letter.creationTime = data.creationTime;
		                    this.letter.id = data.messageID;
		                } else {
		                    console.warn('接收到无效的数据:', res);
		                }
		            },
		            fail: (err) => {
		                console.error('获取信件详情失败:', err);
		            }
		        });
		    },
		    formatDate(date) {
		        const year = date.getFullYear();
		        const month = String(date.getMonth() + 1).padStart(2, '0');
		        const day = String(date.getDate()).padStart(2, '0');
		        const hours = String(date.getHours()).padStart(2, '0');
		        const minutes = String(date.getMinutes()).padStart(2, '0');
		        const seconds = String(date.getSeconds()).padStart(2, '0');
		
		        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		    }
		}
	}
</script>

<style lang="scss">
	.leave_content {
		position: relative;
		padding: 0 0 5px;
		padding-bottom: env(safe-area-inset-bottom);

	}

	.page_body {
		min-height: 100%;
		box-sizing: border-box;
	}

	.max-width {
		max-width: 900rpx;
		margin-left: auto;
		margin-right: auto;
	}

	.treeleavebg {
		position: absolute;
		left: 0;
		right: 0;
		top: -1px;
		bottom: 0;
		min-height: 100vh;
		overflow: hidden;
		background: #13213c;
	}

	.treeleavebg_bg {
		position: absolute;
		left: 0;
		right: 0;
		top: 0;
	}

	.treeleavebg_bg {
		bottom: 0;
		height: 800px;
		background-image: url();
		background-repeat: no-repeat;
		background-position: top;
		background-size: 100% auto;
	}

	.treele_box {
		position: relative;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		overflow-y: auto;
	}

	.treelecho_panel {
		margin: 20px 20px 0;
	}

	.treeleask {
		padding: 10px;
		font-size: 14px;
		line-height: 23px;
		border-radius: 2px;
		color: #fff;
		background: rgba(69, 97, 122, .8);
	}

	.treeleask_box {
		box-sizing: content-box;
		max-height: 90px;
		padding: 5px 0;
		overflow-x: hidden;
		overflow-y: scroll;
	}

	.treeleask_content {
		position: relative;
		padding-left: 12px;
		background-image: url();
		background-position: right 1px top 2px;
		background-size: 20px auto;
		background-repeat: no-repeat;
	}

	.treeleask_content::before {
		content: " ";
		position: absolute;
		left: 0;
		top: 0;
		bottom: 0;
		width: 6px;
		background: #8b9dad;
	}

	.treelecontent {
		text-indent: 28px;
	}

	.treeleask_person {
		display: flex;
		-webkit-box-pack: end;
		justify-content: flex-end;
		-webkit-box-align: center;
		align-items: center;
		max-width: 100%;
		width: fit-content;
		margin: 23px 0 0 auto;
		font-size: 14px;
		text-align: right;
		overflow: hidden;
		cursor: pointer;

	}

	.treeleask_time {
		margin: 2px 0 0;
		font-size: 13px;
		line-height: 1.05;
		text-align: right;
	}

	.treeleask_name {
		font-weight: 700;
	}

	.treelecho_panel+.treelecho_panel {
		margin-top: 14px;
	}

	.treeleanswer {
		padding: 15px;
		font-size: 16px;
		line-height: 28px;
		border-radius: 2px;
		color: #523d14;
		;
		background: #fffbea;
	}


	.treeleanswer_box {
		height: 140px;
		overflow-y: auto;
	}

	.treeleanswer_editor {
		position: relative;
		z-index: 0;
		min-height: 100%;

	}

	.leavetextarea {
		position: relative;
		display: block;
	}

	.treeleanswer_textarea {
		position: relative;
		z-index: 1;
	}

	.treeholeecho_btn-publish {
		color: hsla(0, 0%, 100%, .6);
		background: #868e99;
	}

	.fw-medium {
		font-weight: 600;
	}

	.treeholeecho_btn-publish {
		display: flex;
		-webkit-box-pack: center;
		justify-content: center;
		-webkit-box-align: center;
		align-items: center;
		width: 150px;
		height: 45px;
		margin: 50px auto 0;
		font-size: 16px;
		border-radius: 25px;

	}

	.businesspinbox {
		position: relative;
	}

	.businesspinbox_placeholder {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	.businesspinbox_realbody {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
	}

	.businesspinbox_placeholder {
		visibility: hidden;
	}

	.businesspinbox_fixed {
		position: fixed;
	}

	.businesspinbox_realbody {
		// position: absolute;
		// bottom: 0;
		left: 0;
		right: 0;
		max-width: 390px;
		margin: 0 auto;
	}

	.treeholetoolbar_op {
		position: relative;
		bottom: 0;
		display: flex;
		-webkit-box-align: center;
		align-items: center;
		height: 45px;
		padding: 0 14px;
		color: hsla(0, 0%, 100%, .6);
		background: #273752;
	}

	.treeholetoolbar_anonymous {

		padding: 6px 0;
		font-size: 14px;
		white-space: nowrap;

	}

	.flex {
		display: flex;
	}

	.count {
		flex-grow: 1;
		text-align: right;
	}

	.warning-message {
		position: fixed;
		top: 52%;
		left: 50%;
		transform: translate(-50%, -50%);
		background-color: rgba(125, 125, 125, 0.9);
		color: #ffffff;
		font-size: 16px;
		padding: 10px 20px;
		border-radius: 8px;
		// box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
		z-index: 100;

	}
</style>